<template>
  <scroll-view scroll-y @scrolltolower="onReachBottom" class="balance-log">
    <view class="log-list">
      <view v-for="item in balanceLog" :key="item._id" class="log-item">
        <view class="log-item-left">
          <view class="log-type">{{ getTypeText(item.type) }}</view>
          <view class="log-time">{{ formatDate(item.createdAt) }}</view>
        </view>
        <view class="log-item-right">
          <view :class="['log-amount', item.amount > 0 ? 'income' : 'expense']">
            {{ item.amount > 0 ? "+" : "" }}{{ item.amount }}
          </view>
          <view class="log-order-no" v-if="item.orderNo"
            >订单号：{{ item.orderNo }}</view
          >
        </view>
      </view>
    </view>

    <view class="loading" v-if="loading">加载中...</view>
    <view class="no-more" v-if="noMore">没有更多数据了</view>
  </scroll-view>
</template>

<script setup>
import { ref } from "vue";
import { getBalanceLog } from "@/api/balance";
const balanceLog = ref([]);
import dayjs from "dayjs";

const loading = ref(false);
const noMore = ref(false);
let page = 1;
let pageSize = 10;
let total = 0;

const fetchBalanceLog = async () => {
  if (noMore.value || (page !== 1 && (page - 1) * pageSize >= total)) return;
  loading.value = true;
  try {
    const res = await getBalanceLog({ page, pageSize });
    total = res.data.total;
    balanceLog.value = [...balanceLog.value, ...res.data.list];
    if (balanceLog.value.length === res.data.total) noMore.value = true;
  } finally {
    loading.value = false;
  }
};
const formatDate = (dateStr) => {
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm:ss");
};
const getTypeText = (type) => {
  const typeMap = {
    order: "下单",
    refund: "退款",
    recharge: "充值",
    withdraw: "提现",
  };
  return typeMap[type] || "未知";
};

const onReachBottom = () => {
  page++;
  fetchBalanceLog();
};

fetchBalanceLog();
</script>

<style>
.balance-log {
  height: 100vh;
  background-color: #f5f5f5;
  padding: 12px;
  padding-bottom: calc(12px + var(--status-bar-height));
  box-sizing: border-box;
}

.log-list {
  background-color: #fff;
  border-radius: 12px;
  padding: 0 16px;
}

.log-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item-left {
  flex: 1;
}

.log-type {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.log-time {
  font-size: 12px;
  color: #999;
}

.log-item-right {
  text-align: right;
}

.log-amount {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.income {
  color: #07c160;
}

.expense {
  color: #ee0a24;
}

.log-order-no {
  font-size: 12px;
  color: #999;
}

.loading,
.no-more {
  text-align: center;
  padding: 16px 0;
  color: #999;
  font-size: 14px;
}
</style>
